package testAction.base

import com.sxdz.ApplicationRun
import groovy.json.JsonSlurper
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.SpringApplicationConfiguration
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner
import org.springframework.test.context.web.WebAppConfiguration
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.MvcResult
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder
import org.springframework.test.web.servlet.result.MockMvcResultHandlers
import org.springframework.test.web.servlet.setup.MockMvcBuilders
import org.springframework.web.context.WebApplicationContext

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post


/**
 * Created by lzw on 2016/8/7.
 */

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApplicationRun.class)
@WebAppConfiguration
public class BaseControllerTest  {

    protected final String UTF8 = "UTF-8"
    protected MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    @Before
    public void setMm() {

        mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();

    }

    @Test
    public void testEmpty(){

    }

/**
     * post请求
     * @param url
     * @param map1
     */

    void comm_post(String url,Map map1){

        MockHttpServletRequestBuilder postReq = post(url).characterEncoding(UTF8);
        for (String key : map1.keySet()) {
            postReq.param(key, (String)map1.get(key))
        }
        MvcResult result = this.mockMvc.perform(postReq)
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }

/**
     * get请求
     * @param url
     */

    void comm_get(String url){
        MockHttpServletRequestBuilder getReq =get(url).characterEncoding(UTF8);
        MvcResult result = this.mockMvc.perform(getReq)
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }

    Map getMap_post(String url,Map map1){
        MockHttpServletRequestBuilder postReq = post(url).characterEncoding(UTF8);
        for (String key : map1.keySet()) {
            postReq.param(key, (String)map1.get(key))
        }
                    MvcResult result = this.mockMvc.perform(postReq)
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
        Map result1=  new JsonSlurper().parseText(result.response.getContentAsString()) as Map;
        return result1;
    }
}

